/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.device.server.processor;

import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.frame.structure.Frame;
import com.bugull.farm.core.handler.Processor;
import com.bugull.farm.core.store.Device;
import com.bugull.farm.core.store.User;
import com.bugull.farm.core.store.WifiDevice;
import com.bugull.mongo.BuguDao;
import com.bugull.mongo.cache.DaoCache;

import io.netty.channel.ChannelHandlerContext;

import org.apache.logging.log4j.*;

import java.util.List;

public class DeviceResetProcessor implements Processor {
    
    private final static Logger logger = LogManager.getLogger(DeviceResetProcessor.class);

    @Override
    public void process(ChannelHandlerContext ctx, Frame frame) throws Exception {

        String username = frame.getASCIIStr("username");
        String mac = frame.getHexStr("mac");
        BuguDao<Device> dao = DaoCache.getInstance().get(Device.class);
        Device device = dao.findOne("macAddress", mac);
        if(device == null){
            logger.error("Failed to reset due to the device information of "+mac+" is null!!!");
            ctx.writeAndFlush(frame.getErrorResponse(PropertiesCache.getInstance().getByte("error.refuse")));
            return;
        }
        BuguDao<WifiDevice> wifiDeviceDao = DaoCache.getInstance().get(WifiDevice.class);
        List<WifiDevice> wifiDeviceList = wifiDeviceDao.query().is("macAddress",mac).results();
        User user  = null;
        if(wifiDeviceList != null && wifiDeviceList.size()>0 ){
            for(WifiDevice wifiDevice :wifiDeviceList){
                user = wifiDevice.getUser();
                if( !username.equals(user.getUsername()) ){
                    wifiDeviceDao.remove(wifiDevice.getId());
                }
            }
        }
        ctx.writeAndFlush(frame.getFastResponse());
    }

}
